#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis/hiredis.h>

int main()
{
    // 创建Redis连接
    redisContext *c = redisConnect("192.168.127.128", 6379);
    if (c == NULL) {
        // 如果无法分配redis上下文，直接报错并退出
        printf("Can't allocate redis context\n");
        return 1;
    } else if (c->err) {
        // 如果连接有错误，打印错误信息并释放上下文，然后退出
        printf("Error: %s\n", c->errstr);
        redisFree(c);
        return 1;
    } else {
        // 连接成功时打印消息
        printf("Successfully connected to Redis server\n");
    }

    // 切换到数据库6
    redisReply *reply;
    reply = redisCommand(c, "SELECT 6");
    if (reply == NULL) {
        printf("Error executing SELECT command\n");
        redisFree(c);
        return 1;
    } else if (reply->type == REDIS_REPLY_ERROR) {
        printf("Error reply: %s\n", reply->str);
        freeReplyObject(reply);
        redisFree(c);
        return 1;
    }
    freeReplyObject(reply);

    // 插入一些数据，例如插入一个键值对 "name": "John"
    reply = redisCommand(c, "SET name John");
    if (reply == NULL) {
        printf("Error executing SET command\n");
        redisFree(c);
        return 1;
    } else if (reply->type == REDIS_REPLY_ERROR) {
        printf("Error reply: %s\n", reply->str);
        freeReplyObject(reply);
        redisFree(c);
        return 1;
    }
    freeReplyObject(reply);

    // 可以继续插入更多数据
    reply = redisCommand(c, "SET age 30");
    if (reply == NULL) {
        printf("Error executing SET command\n");
        redisFree(c);
        return 1;
    } else if (reply->type == REDIS_REPLY_ERROR) {
        printf("Error reply: %s\n", reply->str);
        freeReplyObject(reply);
        redisFree(c);
        return 1;
    }
    freeReplyObject(reply);

    redisFree(c);
    return 0;
}
